import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
    View,
    Image,
    StyleSheet,
    Text,
    TextInput,
    Alert
} from 'react-native';

import NccButton from '../components/Button';

import { NavigationScreenProp } from 'react-navigation';
import { scaleSize, scaleFontSize } from "../util/size";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import icons from '../util/icons';
import { request, Storage } from '../util';
import { API_MAP, TOAST_MESSAGE, ROUTERMAP } from '../util/constants';
import UserService from '../service/user';
import { utilValidCheck } from '../util/validCheck';

import * as balanceAction from '../actions/balance';
import * as userAction from '../actions/user';
import * as exchangeBalanceAction from '../actions/exchangeBalance';

interface Iprops {
    navigation: NavigationScreenProp<any, any>,
    // updateBalanceInfo: Function,
    setUser: Function,
    delBalanceInfo: Function,
    updateExchangeBalanceInfo: exchangeBalanceAction.IFuncUpdateExchangeBalanceInfo
}

interface Istate {
    loginBtnDisabled: boolean,
    username: string,
    password: string,
    loginState: string,
    [key: string]: any,
}

const LOGIN_STATE = {
    ready: '登录',
    loading: '登录中...',
}

class LoginView extends Component<Iprops, Istate>{

    constructor(props) {
        super(props);
        this.state = {
            loginBtnDisabled: true,
            username: '',
            password: '',
            loginState: LOGIN_STATE.ready,
        }
    }

    componentDidMount() {
        // 如果用户数据过期后跳转到此页面，传递参数 delUser 为 ture， 删除本地数据 和 redux 中的数据
        const { navigation } = this.props;
        const delUser = navigation.getParam('delUser', false);
        if (delUser) {
            this.props.updateExchangeBalanceInfo({});
            this.props.delBalanceInfo();
            this.props.setUser({});
        }
        Storage.get('username', (err, res) => {
            if (res) {
                console.log('username...', res);
                this.setState({username: res + ''});
            }
        });
    }

    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    };

    handleLogin = async () => {
        const { username, password } = this.state;

        if (!utilValidCheck(username, 'name')) {
            return Alert.alert(TOAST_MESSAGE.LOGIN_FAILED);
        }

        if (!utilValidCheck(password, 'password')) {
            return Alert.alert(TOAST_MESSAGE.INVALID_PASSWORD);
        }

        this.setState({loginState: LOGIN_STATE.loading});

        let res = await request(API_MAP.login, {
            method: 'POST',
            data: {
                name: username,
                password
            }
        }, true);

        this.setState({loginState: LOGIN_STATE.ready});

        Storage.set('username', username);

        if (res.retCode !== '00') {
            if (res.retMsg) {
                return Alert.alert(TOAST_MESSAGE.LOGIN_FAILED);
            }
        }

        if (res.data) {
            let data = res.data;
            UserService.setUser(data);
            this.props.updateExchangeBalanceInfo(data);
            this.props.setUser(data);
            this.turnToPage(ROUTERMAP.home);
        }
    };

    onChangeName = (username) => {
        const newText = username; //.replace(/[^\d]+/, '');
        this.setState({username: newText});
    }

    onChangePwd = (password) => {
        let { username } = this.state;
        if (username && password) {
            this.setState({ password, loginBtnDisabled: false });
        } else {
            this.setState({ password, loginBtnDisabled: true });
        }
    }

    turnToBack = () => {
        // this.props.navigation.back();
        this.props.navigation.goBack();
    };

    render() {
        return (
             <View           
                style={{
                    display: 'flex',
                    flex: 1,
                    backgroundColor: '#4869EE',
                    flexDirection: 'column',
                    // justifyContent: 'center',
                    alignItems: 'center',
                }}>
                <View style={{
                    alignItems: 'flex-end',
                    marginTop: scaleSize(52.8),
                    marginLeft: scaleSize(291.8)
                }}>
                    <Text
                        onPress={() => this.turnToBack()}>
                        <Image source={icons.signClose} style={{
                            width: scaleSize(20),
                            height: scaleSize(20),
                        }} />
                    </Text>
                </View>
                <View
                    style={{ justifyContent: 'center', marginTop: scaleSize(54) }}>
                    <Image source={icons.signLogo}
                        style={{ width: scaleSize(98), height: scaleSize(102) }} />
                </View>

                <KeyboardAwareScrollView>
                <TextInput
                    style={styles.textInputStyle}
                    value={this.state.username}
                    onChangeText={this.onChangeName}  //添加值改变事件
                    maxLength={11}
                    placeholder="输入用户名"
                    placeholderTextColor='white'
                    autoCapitalize={'none'}
                    underlineColorAndroid={'transparent'}
                />
                {/* <Text style={{
                    color: 'red'
                }}>{this.state.inputValue}</Text> */}
                <TextInput
                    onChangeText={this.onChangePwd}  //添加值改变事件
                    maxLength={32}
                    placeholder="输入密码"
                    placeholderTextColor='white'
                    secureTextEntry={true}
                    autoCapitalize={'none'}
                    underlineColorAndroid={'transparent'}
                    style={styles.textInputStyle2}
                />
                <NccButton
                    text={this.state.loginState}
                    textStyle={styles.button1}
                    onPress={this.handleLogin}
                    buttonStyle={{ backgroundColor: 'white', borderRadius: 100, marginTop: scaleSize(16), height: scaleSize(48) }}
                />
                <View
                    style={{
                        flexDirection: 'row',
                        display: 'flex',
                        marginTop: scaleSize(26),
                        // width:scaleSize(295), 
                        justifyContent: 'center',
                    }}>

                    <Text
                        onPress={() => this.turnToPage('ForgetPassword')}
                        style={{ opacity: 0.5, fontFamily: 'PingFangSC-Regular', fontSize: 13, letterSpacing: 1.49, marginRight: scaleSize(27.5), color: 'white' }}>
                        忘记密码
                </Text>
                    <View style={{ width: 1, height: 23, opacity: 0.5, backgroundColor: 'white' }}></View>
                    <Text
                        onPress={() => this.turnToPage('Register')}
                        style={{ opacity: 0.5, fontFamily: 'PingFangSC-Regular', fontSize: 13, letterSpacing: 1.49, marginLeft: scaleSize(27.5), color: 'white' }}>
                        注册账号
                </Text>
                </View>
                </KeyboardAwareScrollView>
            </View>
        );
    }
}

export default connect(
    (state) => ({
        user: state.user,
        balance: state.balance,
    }),
    (dispatch) => ({
        // updateBalanceInfo: (data) => dispatch(balanceAction.updateBalanceInfo(data)),
        delBalanceInfo: () => dispatch(balanceAction.delBalanceInfo()),
        setUser: (data) => dispatch(userAction.setUser(data)),
        updateExchangeBalanceInfo: (data) => dispatch(exchangeBalanceAction.updateBalanceInfo(data)),
    })
)(LoginView);


const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        alignItems: 'center'
    },
    textInputStyle: {
        height: scaleSize(48),
        width: scaleSize(295),
        borderColor: 'rgba(255, 255, 255, 0.5)',
        borderWidth: 1,
        borderRadius: 100,
        fontFamily: 'PingFangSC-Regular',
        textAlign: 'center',
        marginTop: scaleSize(50.2),
        // opacity: 0.3,
        color: 'white',
        letterSpacing: 1.49,

    },
    textInputStyle2: {
        height: scaleSize(48),
        width: scaleSize(295),
        borderColor: 'rgba(255, 255, 255, 0.5)',
        borderWidth: 1,
        borderRadius: 100,
        fontFamily: 'PingFangSC-Regular',
        textAlign: 'center',
        marginTop: scaleSize(16),
        color: 'white',
        letterSpacing: 1.49,
    },
    button1: {
        width: scaleSize(295),
        height: scaleSize(48),
        lineHeight: scaleSize(48),
        color: '#4869EE',
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleFontSize(16),
        textAlign: 'center',

    }
});

// db.clothes.aggregate([
//     {
//         $project: {
//             _id: 1,
//             name: 1,
//             purchase_price: 1,
//             price: 1,
//             items: 1,
//         }
//     },
//     {
//         $unwind: "$items"
//     },
//     {
//         $match: {
//             'items.status': {$in: ['backTo', 'stocked', 'matched']}
//         }
//     },
//     {
//         $group: {
//             _id: {
//                 _id: '$_id',
//                 name: '$name',
//                 purchase_price: '$purchase_price',
//                 price: '$price'
//             },
//             num: {$sum: 1},
//         }
//     },
//     {
//         $project: {
//             name: '$_id.name',
//             _id: '$_id._id',
//             purchase_price: '$_id.purchase_price',
//             price: '$_id.price',
//             num: 1
//         }
//     }
// ]);